package com.jpcc.vw.onlineRadio.utils;


import android.os.RemoteException;
import android.text.TextUtils;

import com.cns.android.authentication.AppTokenInfo;
import com.cns.android.authentication.AppTokenManager;
import com.google.gson.Gson;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.bean.CnsAccountInfoSelf;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukanshan on 2016/12/8.
 */

public class ServiceFactory {

    private static ServiceFactory instance;

    public static ServiceFactory GetInstance() {
        synchronized (ServiceFactory.class) {
            if (instance == null) {
                instance = new ServiceFactory();
            }
        }
        return instance;
    }

    public <S> S createService(Class<S> serviceClass) {
        AppTokenInfo tokenInfo=new Gson().fromJson(PreferenceUtils.GetTokenInfo(),AppTokenInfo.class);
        String url="https://tmuat.cmsp.faw-vw.com/test-access/tm/mos/radio/api/v1/";
        if(tokenInfo!=null&&!TextUtils.isEmpty(tokenInfo.getUrl())){
            url=tokenInfo.getUrl();
        }
        if(!Constants.isRelease){
//            url="https://tmuat.cmsp.faw-vw.com/test-access/tm/mos/radio/api/v1/";
            url=Constants.BASE_URL;
        }
//        url="https://hu-uat.mosc.faw-vw.com/test-access/tm/mos/radio/api/v1/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(serviceClass);
    }


    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        try {
//            setCertificates(builder,MusicApplication.GetInstance().getAssets().open("jpcc.cer"));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //设置超时时间以及App拦截器
        BasicParamsInterceptor paramsInterceptor = null;
        if (Constants.isRelease) {
            File file = new File("/mnt/nfs/onlineapplication.conf");
            if (file.exists()) {
                Logger.i("file exists-->"+file.getAbsolutePath());
                String Authorization = "";
                AppTokenInfo appTokenInfo = new Gson().fromJson(PreferenceUtils.GetTokenInfo(), AppTokenInfo.class);
                if (appTokenInfo == null) {
                    Authorization = "";
                } else {
                    Authorization = appTokenInfo.getToken();
                }
                Logger.i("Authorization-->"+Authorization);
                String TraceId = "";
                String uuid = UUID.randomUUID().toString();
                TraceId = TraceId + uuid;
                Logger.i("TraceId 1-->"+TraceId);
                CnsAccountInfoSelf accountInfo = new Gson().fromJson(PreferenceUtils.GetAccountInfo(), CnsAccountInfoSelf.class);
                if (accountInfo == null) {
                    TraceId = TraceId+"_" + ConfigReaderUtils.readUidFromConfig();
                    Logger.i("TraceId 2-->"+TraceId);
                } else {
                    if ((accountInfo.getType() == 2 || accountInfo.getType() == 3)) {
                        TraceId = TraceId+"_" + "sc";
                    } else {
                        TraceId = TraceId+"_" + accountInfo.getId();
                    }
                    Logger.i("TraceId 3-->"+TraceId);
                }
                String DeviceId = "";
                if (TextUtils.isEmpty(PreferenceUtils.GetDeviceId())) {
                    TraceId = TraceId+"_" + ConfigReaderUtils.readDidFromConfig();
                    DeviceId = ConfigReaderUtils.readDidFromConfig();
                    Logger.i("DeviceId 1-->"+DeviceId);
                } else {
                    TraceId = TraceId + "_" + PreferenceUtils.GetDeviceId();
                    DeviceId = PreferenceUtils.GetDeviceId();
                    Logger.i("DeviceId 2-->"+DeviceId);
                }
                TraceId = TraceId+"_" + System.currentTimeMillis();
                Logger.i("TraceId 4-->"+TraceId);
                paramsInterceptor =
                        new BasicParamsInterceptor.Builder()
                                .addHeaderParam("Content-Type", "application/json")
                                .addHeaderParam("Authorization", "Bearer "+Authorization)
                                .addHeaderParam("Content-Type", "application/json")
                                .addHeaderParam("TraceId", TraceId)
                                .addHeaderParam("Accept-Language", "zh-CN")
                                .addHeaderParam("Accept", "application/json; charset=utf-8")
                                .addHeaderParam("Did", ("VW_HU_"+"CNS3_"+DeviceId+"_v1.0.1"+"_v0.0.1").replace(" ",""))
                                .addHeaderParam("clientOsType", "2")
                                .addHeaderParam("Timestamp", String.valueOf(System.currentTimeMillis()))
                                .build();
            } else {
                paramsInterceptor =
                        new BasicParamsInterceptor.Builder()
                                .addHeaderParam("Content-Type", "application/json")
                                .addHeaderParam("Authorization", "Bearer "+Constants.DEAFAULTOKEN)
                                .addHeaderParam("Content-Type", "application/json")
                                .addHeaderParam("TraceId", Constants.DEFAULT_TRACEID)
                                .addHeaderParam("Accept-Language", "zh-CN")
                                .addHeaderParam("Accept", "application/json; charset=utf-8")
                                .addHeaderParam("Did", "VW_HU_"+"CNS3_"+"862446000000312"+"_v1.0.1"+"_v0.0.1")
                                .addHeaderParam("clientOsType", "2")
                                .addHeaderParam("Timestamp", String.valueOf(System.currentTimeMillis()))
                                .build();
            }

        } else {
            paramsInterceptor =
                    new BasicParamsInterceptor.Builder()
                            .addHeaderParam("Content-Type", "application/json")
                            .addHeaderParam("Authorization", "Bearer "+Constants.DEAFAULTOKEN)
                            .addHeaderParam("Content-Type", "application/json")
                            .addHeaderParam("TraceId", Constants.DEFAULT_TRACEID)
                            .addHeaderParam("Accept-Language", "zh-CN")
                            .addHeaderParam("Accept", "application/json; charset=utf-8")
                            .addHeaderParam("Did", "VW_HU_"+"CNS3_"+"862446000000312"+"_v1.0.1"+"_v0.0.1")
//                            .addHeaderParam("Did","CNS3_"+"GRO-63301.10.23242312"+"_v1.0.1"+"_v0.0.1")
                            .addHeaderParam("clientOsType", "2")
                            .addHeaderParam("Timestamp", String.valueOf(System.currentTimeMillis()))
                            .build();
        }
        try {
            if(Constants.isRelease){
                String certificate = AppTokenManager.getInstance(MusicApplication.GetInstance()).getHttpsCertificate();
                Logger.i("ServiceFactory----getHttpsCertificate--->>>"+certificate);
                String privateKey = AppTokenManager.getInstance(MusicApplication.GetInstance()).getHttpsPrivateKey();
                Logger.i("ServiceFactory----getprivateKey--->>>"+privateKey);
                SSLUtils.SSLParams sslParams=null;
                if (!TextUtils.isEmpty(certificate) && !TextUtils.isEmpty(privateKey)) {
                    File file = new File(certificate);
                    if (file != null && file.exists()) {
                        Logger.i("bks File exist");
                        try {
                            sslParams = SSLUtils.getSslSocketFactory(new FileInputStream(file),
                                    privateKey, SSLUtils.UnSafeTrustManager);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
//                InputStream inputStream=MusicApplication.GetInstance().getResources().getAssets().open("client_svw.bks");
//                sslParams = SSLUtils.getSslSocketFactory(inputStream,"123456", SSLUtils.UnSafeTrustManager);

                builder.connectTimeout(10, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(false)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager)
                        .hostnameVerifier(SSLUtils.UnSafeHostnameVerifier)
                        .addInterceptor(paramsInterceptor);
            }
            else{


                SSLUtils.SSLParams sslParams=null;
                InputStream inputStream=MusicApplication.GetInstance().getResources().getAssets().open("client.bks");
                sslParams = SSLUtils.getSslSocketFactory(inputStream,"123456", SSLUtils.UnSafeTrustManager);

                builder.connectTimeout(10, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(false)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager)
                        .hostnameVerifier(SSLUtils.UnSafeHostnameVerifier)
                        .addInterceptor(paramsInterceptor);
            }

        }catch (IOException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        OkHttpClient client = builder.build();
        return client;
    }
}
